package com.qf.cs2203Spring07.DispatchServlet;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

@WebServlet(name = "DispatchServlet", urlPatterns = "/", loadOnStartup = 1)
public class DispatchServlet extends HttpServlet {

    private ApplicationContext context;
    private Properties ps;

    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("servlet 启动了");

        context = new ClassPathXmlApplicationContext("classpath:beans.xml");

        ps = new Properties();
        ServletContext application = this.getServletContext();
        try {
            ps.load(application.getResourceAsStream("/WEB-INF/dispachServlet.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//        String method = request.getParameter("method");
//        System.out.println("请求来了 请求的地址是："+ request.getServletPath());
        String path = request.getServletPath();
        String methodName = request.getParameter("method");
        String className = ps.getProperty(path);

        System.out.println("页面上请求的路径是：" + path);
        System.out.println("路径对应的类："+className);
        System.out.println("执行类中的方法是："+ methodName);

        try {
            Class clazz = Class.forName(className);
            Object bean = context.getBean(clazz);

            Method method = clazz.getDeclaredMethod(methodName,HttpServletRequest.class);
            Object invoke = method.invoke(bean, request);
            System.out.println("invoke="+invoke);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doGet(request, response);
    }

}
